package top.infopub.job.fia.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.enums.fia.OrgSumTypesEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.job.fia.dao.BudgetDao;
import top.infopub.job.fia.domain.BudgetSumDomain;
import top.infopub.job.fia.service.BudgetService;
import top.infopub.job.hr.dao.OrgInfoDao;
import top.infopub.model.fia.Budget;
import top.infopub.model.fia.BudgetSummary;
import top.infopub.model.fia.BudgetTask;
import top.infopub.model.hr.OrgInfo;

import java.util.Date;
import java.util.List;

@Service
public class BudgetServiceImpl extends GenericServiceImpl<Budget, String> implements
        BudgetService {
    private static final Logger log = LoggerFactory.getLogger(BudgetServiceImpl.class);

	@Autowired
	private BudgetDao budgetDao;

	@Autowired
    private OrgInfoDao orgInfoDao;
	
	@Override
	public GenericDao<Budget, String> getDao() {
		return budgetDao;
	}

    @Override
    @Transactional
    public void budgetSummary() {
        List<BudgetTask> taskList = budgetDao.queryBudgetTaskList("0");
        if (taskList != null && taskList.size() > 0) {
            log.info("预算管理待汇总数量：{}", taskList.size());
            for (BudgetTask task : taskList) {
                if (task == null) continue;
                //统计金额
                BudgetSumDomain bsd = budgetDao.queryBudgetSumById(task.getBudgetId());
                if (bsd == null) continue;
                //统计金额-所属公司
                OrgInfo thisOrg = orgInfoDao.selectByPrimaryKey(bsd.getHrOrgId());
                if (thisOrg == null) continue;
                //查询上级公司-需要查询到TYPES=2或TYPES=1为止
                OrgInfo parentOrg = orgInfoDao.selectByPrimaryKey(thisOrg.getParentId());
                while (true) {
                    if (parentOrg == null) break;
                    if (StringUtils.equals(OrgSumTypesEnum.ORG_SUM_TYPES1.getCode(), parentOrg.getTypes())
                            || StringUtils.equals(OrgSumTypesEnum.ORG_SUM_TYPES2.getCode(), parentOrg.getTypes())) break;
                    parentOrg = orgInfoDao.selectByPrimaryKey(parentOrg.getParentId());
                }
                //汇总名称设置
                OrgSumTypesEnum oste = getOrgSumTypes(thisOrg, parentOrg);
                //设置默认名称
                String name = oste.getName();
                //如果得到的枚举类为1=总部，设置名称为公司名称
                if (StringUtils.equals(OrgSumTypesEnum.ORG_SUM_TYPES1.getCode(), oste.getCode())) {
                    name = thisOrg.getCompName();
                }
                BudgetSummary bs = new BudgetSummary();
                BeanUtils.copyProperties(bsd, bs);
                bs.setOrgTypes(thisOrg.getTypes());
                bs.setOrgSumTypes(oste.getCode());
                bs.setUptBy(bsd.getAddBy());
                bs.setUptTime(new Date());
                bs.setName(name);
                //根据所属公司和归属年月查询汇总记录
                BudgetSummary tmpBs = budgetDao.queryByOrgIdAndBelongDate(thisOrg.getId(), bsd.getBudgetYear());
                //原来累加到区域公司/总部的金额
                BudgetSummary oldBs = new BudgetSummary();
                //项目公司或直属项目公司汇总自己当前的信息
                if (tmpBs == null) {
                    bs.setAddTime(new Date());
                    budgetDao.insertBudgetSummary(bs);
                } else {
                    bs.setId(tmpBs.getId());
                    BeanUtils.copyProperties(tmpBs, oldBs);
                    budgetDao.updateBudgetSummary(bs);
                }
                //找到汇总的项目公司/直属项目公司对应的区域公司或总部，进行金额累计
                while (parentOrg != null) {
                    //所属公司-TYPES为1或2
                    thisOrg = orgInfoDao.selectByPrimaryKey(parentOrg.getId());
                    //查询上级公司
                    parentOrg = orgInfoDao.selectByPrimaryKey(thisOrg.getParentId());
                    //汇总名称设置
                    oste = getOrgSumTypes(thisOrg, parentOrg);
                    //设置默认名称
                    name = oste.getName();
                    //如果得到的枚举类为1=总部，设置名称为公司名称
                    if (StringUtils.equals(OrgSumTypesEnum.ORG_SUM_TYPES1.getCode(), oste.getCode())) {
                        name = thisOrg.getCompName();
                    }
                    //根据所属公司和归属年月查询汇总记录
                    tmpBs = budgetDao.queryByOrgIdAndBelongDate(thisOrg.getId(), bsd.getBudgetYear());
                    bs = new BudgetSummary();
                    BeanUtils.copyProperties(bsd, bs);
                    bs.setHrOrgId(thisOrg.getId());
                    bs.setOrgTypes(thisOrg.getTypes());
                    bs.setOrgSumTypes(oste.getCode());
                    bs.setUptBy(bsd.getAddBy());
                    bs.setUptTime(new Date());
                    bs.setName(name);
                    if (tmpBs == null) {
                        bs.setAddTime(new Date());
                        budgetDao.insertBudgetSummary(bs);
                    } else {
                        //先把以前累计的金额扣除在把新的金额累计上去
                        bs.setId(tmpBs.getId());
                        budgetDao.updateBudgetSummary(bs);
                    }
                }
                budgetDao.updateBudgetTaskStatus("1", task.getId());
            }
        }
    }

    private OrgSumTypesEnum getOrgSumTypes(OrgInfo thisOrg, OrgInfo parentOrg) {
	    //上级公司不为空
        if (parentOrg != null) {
            //如果上级公司类型为1=总部
            if (StringUtils.equals(OrgSumTypesEnum.ORG_SUM_TYPES1.getCode(), parentOrg.getTypes())) {
                if (StringUtils.equals(OrgSumTypesEnum.ORG_SUM_TYPES1.getCode(), thisOrg.getTypes())) {
                    //如果当前公司类型为1=总部，
                    return OrgSumTypesEnum.ORG_SUM_TYPES1;
                } else if (StringUtils.equals(OrgSumTypesEnum.ORG_SUM_TYPES3.getCode(), thisOrg.getTypes())) {
                    //如果当前公司类型为3=项目公司，返回项目直属公司
                    return OrgSumTypesEnum.ORG_SUM_TYPES4;
                }
            }
            //如果上级公司是2=区域公司/3=项目公司，返回当前公司类型对应的枚举类
            return OrgSumTypesEnum.getByCode(thisOrg.getTypes());
        }
        //上级公司不存在，默认为最顶级的1=总部
        return OrgSumTypesEnum.ORG_SUM_TYPES1;
    }

    /**
     * 重新设置金额
     * @param bs 待更新的汇总类
     * @param oldBs 项目公司/直属项目公司旧数据
     * @param tmpBs 区域公司/总部数据
     */
    private void setBudgetSummaryAmt(BudgetSummary bs, BudgetSummary oldBs, BudgetSummary tmpBs) {
        bs.setTiredAmt(tmpBs.getTiredAmt().subtract(oldBs.getTiredAmt()).add(bs.getTiredAmt()));
        bs.setLastM11(tmpBs.getLastM11().subtract(oldBs.getLastM11()).add(bs.getLastM11()));
        bs.setLastM12(tmpBs.getLastM12().subtract(oldBs.getLastM12()).add(bs.getLastM12()));
        bs.setYearTotal(tmpBs.getYearTotal().subtract(oldBs.getYearTotal()).add(bs.getYearTotal()));
        bs.setM1(tmpBs.getM1().subtract(oldBs.getM1()).add(bs.getM1()));
        bs.setM2(tmpBs.getM2().subtract(oldBs.getM2()).add(bs.getM2()));
        bs.setM3(tmpBs.getM3().subtract(oldBs.getM3()).add(bs.getM3()));
        bs.setM4(tmpBs.getM4().subtract(oldBs.getM4()).add(bs.getM4()));
        bs.setM5(tmpBs.getM5().subtract(oldBs.getM5()).add(bs.getM5()));
        bs.setM6(tmpBs.getM6().subtract(oldBs.getM6()).add(bs.getM6()));
        bs.setM7(tmpBs.getM7().subtract(oldBs.getM7()).add(bs.getM7()));
        bs.setM8(tmpBs.getM8().subtract(oldBs.getM8()).add(bs.getM8()));
        bs.setM9(tmpBs.getM9().subtract(oldBs.getM9()).add(bs.getM9()));
        bs.setM10(tmpBs.getM10().subtract(oldBs.getM10()).add(bs.getM10()));
        bs.setM11(tmpBs.getM11().subtract(oldBs.getM11()).add(bs.getM11()));
        bs.setM12(tmpBs.getM12().subtract(oldBs.getM12()).add(bs.getM12()));
    }
}